#include "http.h"

#include <QEventLoop>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <qmessagebox.h>

Http::Http(QObject *parent) : QObject(parent)
{

}

bool Http::post_sync(QString url, QMap<QString, QString> head, QByteArray requestContext, QByteArray &responseContext)
{
    // 发送请求的对象
    QNetworkAccessManager manager;
    // 请求对象
    QNetworkRequest request;
    request.setUrl(url);
    QMapIterator<QString, QString> it(head);
    while (it.hasNext()) {
        it.next();
        request.setRawHeader(it.key().toLatin1(), it.value().toLatin1());
    }

    QNetworkReply *reply =  manager.post(request, requestContext);
    QEventLoop l;
    // 一旦服务器返回，reply会发出信号
    connect(reply, &QNetworkReply::finished, &l, &QEventLoop::quit);
    l.exec(); // 死循环，reply发出信号，结束循环

    if (reply != nullptr && reply->error() == QNetworkReply::NoError) {
        // 服务器返回的数据
        responseContext = reply->readAll();
        return true;
    } else {
        QMessageBox::warning(nullptr, "请求失败", "请检查联网是否稳定");
        return false;
    }

}

